package com.whl.sm.service.impl.dynamic;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.mapper.dynamic.LikeOperateMapper;
import com.whl.sm.model.dynamic.LikeOperate;
import com.whl.sm.model.dynamic.VDynamic;
import com.whl.sm.service.dynamic.LikeOperateService;
import com.whl.sm.service.dynamic.VDynamicService;
import com.whl.sm.service.system.OrgUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2022-02-17
 */
@Slf4j
@Service
public class LikeOperateServiceImpl extends ServiceImpl<LikeOperateMapper, LikeOperate> implements LikeOperateService {

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private VDynamicService vDynamicService;


    private Result update(LikeOperate likeOperate){
        try {
            if (Objects.isNull(likeOperate.getId())){
                getBaseMapper().insert(likeOperate);
            }else {
                getBaseMapper().updateById(likeOperate);
            }
        }catch (Exception e){
            log.error("更新失败---------->"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    public Result likeOperate(String id, String type) {
        String userId = orgUserService.getCurrentUserId();
        if (Objects.isNull(userId)){
            return Result.fail();
        }
        try {
            if (type.equals("like")){
                VDynamic linkDynamic = vDynamicService.getById(id);
                linkDynamic.setLikeCount(linkDynamic.getLikeCount()+1);
                vDynamicService.update(linkDynamic);
                LikeOperate insert = new LikeOperate();
                insert.setDynamicId(id);
                insert.setOperate(userId);
                insert.setCreateTime(new Date());
                update(insert);
            }else {
                List<LikeOperate> likeOperates = getBaseMapper().selectList(new QueryWrapper<LikeOperate>()
                        .eq("dynamic_id",id)
                        .eq("operate",userId)
                );
                for (LikeOperate item: likeOperates) {
                    getBaseMapper().deleteById(item.getId());
                }
            }
        }catch (Exception e){
            log.error("点赞操作失败----->"+e);
            return Result.fail();
        }
        return Result.ok();
    }
}
